//
//  MNDFinanceDetailViewController.m
//  minidai
//
//  Created by 谭谭伟 on 17/5/21.
//  Copyright © 2017年 迷你金服. All rights reserved.
//
#pragma mark -HR详情页

#import "MNDFinanceDetailViewController.h"
#import "MNDFinanceDescribleViewController.h"
#import "MNDFinanceRecordViewController.h"
#import "MNDTenderInfoViewController.h"
#import "MNDTransferRecordViewController.h"
#import "WMPanGestureRecognizer.h"
#import "MNDFinaceDetailModel.h"
#import "MNDFinanceViewController.h"
#import "MNDInvestModel.h"
#import "MNDLoginUserModel.h"
#import "MNDFinanceAlertViewController.h"
@interface MNDFinanceDetailViewController ()<UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIView *topScrollView;
@property (nonatomic, strong) WMPanGestureRecognizer *panGesture;
@property (nonatomic, assign) CGPoint lastPoint;
@property (nonatomic,strong) MNDFinaceDetailModel *detaiModel;
//借款标题
@property (weak, nonatomic) IBOutlet UILabel *borrowTitleLabel;
//借款年利率
@property (weak, nonatomic) IBOutlet UILabel *borrowYearAprLabel;
//借款期限
@property (weak, nonatomic) IBOutlet UILabel *borrowDeadlineLabel;
//借款最低投资
@property (weak, nonatomic) IBOutlet UILabel *leastMoneyLabel;
//剩余可投
@property (weak, nonatomic) IBOutlet UILabel *remainingableTenderLabel;
//借款总额
@property (weak, nonatomic) IBOutlet UILabel *borrowMoneyLabel;
//回款方式
@property (weak, nonatomic) IBOutlet UILabel *backWayLabel;
//起息日期
@property (weak, nonatomic) IBOutlet UILabel *borrowStartDateLabel;
//发布时间
@property (weak, nonatomic) IBOutlet UILabel *borrowReleaseTimeLabel;

//投资数据
@property (strong, nonatomic) MNDInvestModel *investModel;

@property (weak, nonatomic) IBOutlet UIProgressView *progressView;

@property (weak, nonatomic) IBOutlet UILabel *progressLabel;

@property (strong ,nonatomic) MNDFinanceDescribleViewController *describleVC;
@property (strong ,nonatomic) MNDFinanceRecordViewController *financeRecordVC;
@property (strong ,nonatomic) MNDTenderInfoViewController *tenderInfoVC;
@property (strong ,nonatomic) MNDTransferRecordViewController *transferRecordVC;
//投资按钮
@property (strong,nonatomic) UIButton *investButton;

@property (strong,nonatomic) UIButton *moreContentButton;

@property (weak, nonatomic) IBOutlet UIButton *transferConditionButton;


@end

@implementation MNDFinanceDetailViewController

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    self.menuItemWidth = kScreenWidth*0.25;
    self.menuViewStyle = WMMenuViewStyleLine;
    self.titleSizeSelected = 14.0;
    self.titleSizeNormal = 14.0;
    self.titleColorNormal = [UIColor blackColor];
    self.titleColorSelected = [UIColor colorWithRed:237/255.0 green:129/255.0 blue:100/255.0 alpha:1.0];
    self.menuBGColor = [UIColor whiteColor];
    self.viewTop = kWMHeaderViewHeight + kNavigationBarHeight;
    self.viewFrame = CGRectMake(0,kWMHeaderViewHeight + kNavigationBarHeight, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    return self;
}

- (NSArray<NSString *> *)titles {
    return @[@"借款信息",@"出借记录",@"债权信息",@"转让记录"];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"出借详情";
    self.panGesture = [[WMPanGestureRecognizer alloc] initWithTarget:self action:@selector(panOnView:)];
    [self.view addGestureRecognizer:self.panGesture];
    [self loadData];
    [self setupUI];
    self.scrollView.delegate = self;
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //导航条透明
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
}

#pragma mark -加载数据
- (void)loadData {
    [NetworkProgressHUD showHud];
    __weak typeof(self) weakSelf = self;
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"borrow_code":self.brrowCode}];
    
    [APIManager sendRequestWithPath:API_FINANCE_DETAIL parameters:params method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            weakSelf.detaiModel = [MNDFinaceDetailModel mj_objectWithKeyValues:responseModel.data];
            [weakSelf configContents];
        } else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

//获取投资赠利券数据
- (void)loadInvestData{
    WeakSelf(self)
    //请求投资
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"borrow_code":self.detaiModel.borrow_code}];
    
    [APIManager sendRequestWithPath:API_INVEST parameters:params method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if(responseModel.status == ResponseSuccess) {
            weakself.investModel = [MNDInvestModel mj_objectWithKeyValues:responseModel.data];
            
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}


- (void)configContents {
    self.borrowTitleLabel.text = self.detaiModel.borrow_title;
    self.borrowYearAprLabel.text = self.detaiModel.borrow_year_apr;
    self.borrowDeadlineLabel.text = [NSString stringWithFormat:@"%@个月",self.detaiModel.borrow_deadline];
    self.leastMoneyLabel.text = [NSString stringWithFormat:@"%@元",self.detaiModel.borrow_least_tender];
    self.remainingableTenderLabel.text = [NSString stringWithFormat:@"%@",self.detaiModel.remainingable_tender];
    self.borrowMoneyLabel.text = [NSString stringWithFormat:@"%@元",self.detaiModel.borrow_money];
    self.backWayLabel.text = self.detaiModel.back_way;
    self.borrowStartDateLabel.text = self.detaiModel.borrow_start_date;
    self.borrowReleaseTimeLabel.text = self.detaiModel.borrow_release_time;
    NSString *progressStr = self.detaiModel.borrow_nowProgress;
    CGFloat number = progressStr.integerValue;
    CGFloat progressNum = number/100;
    self.progressView.progress = progressNum;
    
    if (self.detaiModel.borrow_deadline.integerValue > 2) {
        [self.transferConditionButton setTitle:@"满60天后可转" forState:UIControlStateNormal];
    } else {
    [self.transferConditionButton setTitle:@"短期标不可转" forState:UIControlStateNormal];
    }
    if (self.detaiModel.borrow_nowProgress) {
            NSString *progressStr = self.detaiModel.borrow_nowProgress;
            NSInteger number = progressStr.integerValue;
            //        CGFloat number1 = number;
            NSString *progress = [NSString stringWithFormat:@"%ld",(long)number];
            //        [self.progressViewConstraint setValue:progress forKey:@"multiplier"];
            NSString *precent = @"%";
            self.progressLabel.text = [NSString stringWithFormat:@"%@%@",progress,precent];
    }
    if ([self.detaiModel.borrow_status isEqualToString:@"2"]) {
        self.investButton.userInteractionEnabled = YES;
        [self.investButton setBackgroundImage:[UIImage imageNamed:@"finance_invest_btn"] forState:UIControlStateNormal];
    } else {
        self.investButton.userInteractionEnabled = NO;
        [self.investButton setBackgroundImage:nil forState:UIControlStateNormal];
        [self.investButton setBackgroundColor:[UIColor colorWithRed:181/255.0 green:181/255.0 blue:181/255.0 alpha:1.0]];
    }

    self.describleVC.brrowContent = self.detaiModel.borrow_content;
    self.describleVC.brrowImg = self.detaiModel.borrow_img;
    self.financeRecordVC.tender = self.detaiModel.tender;
    self.tenderInfoVC.creditor = self.detaiModel.creditor;
    self.transferRecordVC.transfer = self.detaiModel.transfer;
}

#pragma mark -搭建界面
- (void)setupUI {
    //在menuView下面添加下划线
    UIView *bottomLine = [[UIView alloc]init];
    bottomLine.backgroundColor = kColorLightGrayLine;
    [self.menuView addSubview:bottomLine];
    [bottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(1);
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.menuView.mas_bottom);
    }];
    //立即投资按钮
    UIButton *investButton = [[UIButton alloc] init];
    [investButton setTitle:@"确认出借" forState:UIControlStateNormal];
    [investButton setBackgroundImage:[UIImage imageNamed:@"finance_invest_btn"] forState:UIControlStateNormal];
    [self.view insertSubview:investButton atIndex:100];
    self.investButton = investButton;
    //添加点击事件
    [investButton addTarget:self action:@selector(goInvest:) forControlEvents:UIControlEventTouchUpInside];
    [investButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.mas_equalTo(self.view);
        make.height.mas_equalTo(44);
    }];
    
    //查看更多按钮
    UIButton *moreContentButton = [[UIButton alloc] init];
    [moreContentButton setTitle:@"向上拖动查看更多信息" forState:UIControlStateNormal];
    [moreContentButton setBackgroundColor:[UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:1.0]];
    [moreContentButton setTitleColor:[UIColor colorWithRed:180/255.0 green:187/255.0 blue:192/255.0 alpha:1.0] forState:UIControlStateNormal];
    moreContentButton.titleEdgeInsets = UIEdgeInsetsMake(0, 15 , 0, 0);
    [moreContentButton setImage:[UIImage imageNamed:@"finance_detail_load_more"] forState:UIControlStateNormal];
    moreContentButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [self.view insertSubview:moreContentButton atIndex:100];
    [moreContentButton addTarget:self action:@selector(clickCheckMore:) forControlEvents:UIControlEventTouchUpInside];
    [moreContentButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.view);
        make.bottom.mas_equalTo(investButton.mas_top);
        make.height.mas_equalTo(40);
    }];
    self.moreContentButton =  moreContentButton;
    self.moreContentButton.hidden = YES;
}
     

//手势滑动
- (void)panOnView:(WMPanGestureRecognizer *)recognizer {
    if (self.topScrollView.frame.origin.y == 0) {
        self.moreContentButton.hidden = YES;
    }else {
        self.moreContentButton.hidden = YES;
    }
    NSLog(@"-------%lf---------",self.topScrollView.frame.origin.y);
    NSLog(@"pannnnnning received..");
    CGPoint currentPoint = [recognizer locationInView:self.view];
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        self.lastPoint = currentPoint;
    } else if (recognizer.state == UIGestureRecognizerStateChanged) {
        
        CGPoint velocity = [recognizer velocityInView:self.view];
        CGFloat targetPoint = velocity.y < 0 ? kNavigationBarHeight : kNavigationBarHeight + kWMHeaderViewHeight;
        NSTimeInterval duration = fabs((targetPoint - self.viewTop) / velocity.y);
        
        if (fabs(velocity.y) * 1.0 > fabs(targetPoint - self.viewTop)) {
            NSLog(@"velocity: %lf", velocity.y);
            [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
                
                self.viewTop = targetPoint;
                self.topScrollView.transform = CGAffineTransformMakeTranslation(0, -(kWMHeaderViewHeight+kNavigationBarHeight-self.viewTop));
            } completion:nil];
            
            return;
        }
    }
//    self.moreContentButton.hidden = NO;
    CGFloat yChange = currentPoint.y - self.lastPoint.y;
    self.viewTop += yChange;
    self.topScrollView.transform = CGAffineTransformMakeTranslation(0, -(kWMHeaderViewHeight+kNavigationBarHeight-self.viewTop));
    self.lastPoint = currentPoint;
}


- (void)setViewTop:(CGFloat)viewTop {
    
    _viewTop = viewTop;
    
    if (_viewTop <= kNavigationBarHeight) {
        _viewTop = kNavigationBarHeight;
    }
    
    if (_viewTop > kWMHeaderViewHeight + kNavigationBarHeight) {
        _viewTop = kWMHeaderViewHeight + kNavigationBarHeight;
    }
    
    self.viewFrame = CGRectMake(0, _viewTop, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
}

- (NSInteger)numbersOfChildControllersInPageController:(WMPageController *)pageController {
    return self.titles.count;
}

- (UIViewController *)pageController:(WMPageController *)pageController viewControllerAtIndex:(NSInteger)index {
    if (index == 0) {
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Finance" bundle:nil];
        MNDFinanceDescribleViewController *describleVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDFinanceDescribleViewController"];
        self.describleVC = describleVC;
        describleVC.brrowContent = self.detaiModel.borrow_content;
        return describleVC;
    }else if(index == 1){
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Finance" bundle:nil];
        MNDFinanceRecordViewController *financeRecordVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDFinanceRecordViewController"];
        financeRecordVC.tender = self.detaiModel.tender;
        self.financeRecordVC = financeRecordVC;
        return financeRecordVC;
    }else if (index == 2){
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Finance" bundle:nil];
        MNDTenderInfoViewController *tenderInfoVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDTenderInfoViewController"];
        self.tenderInfoVC = tenderInfoVC;
        tenderInfoVC.creditor = self.detaiModel.creditor;
        return tenderInfoVC;
    }else {
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Finance" bundle:nil];
        MNDTransferRecordViewController *transferRecordVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDTransferRecordViewController"];
        transferRecordVC.transfer = self.detaiModel.transfer;
        self.transferRecordVC = transferRecordVC;
        return transferRecordVC;
    }
}

#pragma mark -立即投资按钮事件
- (void)goInvest:(UIButton *)sender {
    if ([MNDLoginUserModel isUserLogin]) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Finance" bundle:[NSBundle mainBundle]];
        MNDFinanceViewController *financeVC = [storyboard instantiateViewControllerWithIdentifier:@"financeVC"];
        financeVC.borrowCode = self.detaiModel.borrow_code;
        [self.navigationController pushViewController:financeVC animated:YES];
    }else {
        [self goToLoginVC];
    }
}

- (IBAction)transferConditionAction:(UIButton *)sender {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    __weak MNDFinanceAlertViewController *alertVC = [storyboard instantiateViewControllerWithIdentifier:@"MNDFinanceAlertViewController"];
    __weak UIView *springView = alertVC.view;
    [KeyWindow addSubview:springView];
    [self addChildViewController:alertVC];
    [alertVC.alertBtn bk_addEventHandler:^(id sender) {
        [UIView animateWithDuration:0.5 animations:^{
            alertVC.alertContainView.frame = CGRectMake(alertVC.alertContainView.frame.origin.x, kScreenHeight, alertVC.alertContainView.frame.size.width, alertVC.alertContainView.frame.size.height);
        } completion:^(BOOL finished) {
            [springView removeFromSuperview];
            [alertVC removeFromParentViewController];
        }];

    } forControlEvents:UIControlEventTouchUpInside];
    

}

- (void)clickCheckMore:(UIButton*)sender {

    
    
}

#pragma mark -没有登录，跳转到登录页面

- (void)goToLoginVC {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
    UINavigationController *naviVC = [storyboard instantiateInitialViewController];
    
    [self presentViewController:naviVC animated:YES completion:^{
        
    }];
}
//
//- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//
//
//}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
